package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    @RequestMapping("/ajax")
    public String doAjax() {
        return "doajax";
    }

    private List<Map<String, Object>> list = new LinkedList<>();
    Map<String, Object> map = new HashMap<>();

    public AjaxController() {
        map.put("huawei", 6000);
        map.put("xiaomi", 5000);
        map.put("oppo", 4000);
        list.add(map);
    }

    @GetMapping("/doAjaxGet")//只能处理get请求
    @ResponseBody
    public List<Map<String, Object>> doAjaxGet() {
        return list;
    }

    @ResponseBody
    @PostMapping("/doAjaxPost")//@RequestParam 接受客户端传来的（send）post参数
    public List<Map<String, Object>> doAjaxPost(@RequestParam Map<String, Object> map) {
        list.add(map);
        return list;
    }

    @ResponseBody
    @DeleteMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable String id) {
        for (Map<String, Object> map :
                list) {
            if (map.get("id").equals(id)) {
                map.remove("id");
            }
        }
        return "delete ok";
    }

    @ResponseBody
    @PutMapping("/doAjaxPut")
    public String doAjaxPut(@RequestParam Map<String, Object> map) {
        String id = (String) map.get("id");
        Iterator<Map<String, Object>> iterator = list.iterator();
        Map<String, Object> map1 = null;
        while (iterator.hasNext()) {
            map1 = iterator.next();
            if (map1.get("id").equals(id)) {
                break;
            }

        }
        map1.put("name", map.get("name"));
        map1.put("remark", map.get("remark"));
        return "update ok";
    }
}
